package com.hotel.inventory.service;

import com.hotel.inventory.entity.Product;
import com.hotel.inventory.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    // 查询所有未删除商品
    public List<Product> getAllValidProducts() {
        return productRepository.findByIsDeletedFalse();
    }

    // 根据ID查询商品
    public Product getProductById(Long id) {
        return productRepository.findByIdAndIsDeletedFalse(id);
    }

    // 保存/更新商品（新增时isDeleted默认为false）
    @Transactional
    public Product saveProduct(Product product) {
        if (product.getId() == null) {
            product.setIsDeleted(false);
        }
        return productRepository.save(product);
    }

    // 更新库存（简单实现，实际需记录库存变更日志）
    @Transactional
    public Product updateStock(Long id, Integer newStock) {
        Product product = getProductById(id);
        if (product != null) {
            product.setStock(newStock);
            return productRepository.save(product);
        }
        return null;
    }

    // 逻辑删除商品
    @Transactional
    public boolean deleteProduct(Long id) {
        Product product = getProductById(id);
        if (product != null) {
            product.setIsDeleted(true);
            productRepository.save(product);
            return true;
        }
        return false;
    }
}